package dao

import (
	"bilibi.com/comment/model"
	"context"
	"encoding/json"
	"fmt"
	"time"
)

const (
	_commentKey = "co_%d" // set fi_id value:comment
)

func commentKey(id int64) string {
	return fmt.Sprintf(_commentKey, id)
}

func (d *Dao) ExpireComment(c context.Context, id int64) (ok bool, err error) {
	key := commentKey(id)
	ok, err = d.redis.Expire(key, time.Hour).Result()
	return
}

func (d *Dao) AddCommentCache(c context.Context, id int64, comment *model.Comment) (err error) {
	var value []byte
	key := commentKey(id)
	if value, err = json.Marshal(comment); err != nil {
		return
	}
	err = d.redis.Set(key, value, time.Hour).Err()
	return
}

func (d *Dao) GetCommentCache(c context.Context, id int64) (res *model.Comment, err error) {
	key := commentKey(id)
	value, err := d.redis.Get(key).Result()
	if err != nil {
		return
	}
	err = json.Unmarshal([]byte(value), &res)
	if err != nil {
		return
	}
	return
}

func (d *Dao) DelCommentCache(c context.Context, id int64) (err error) {
	key := commentKey(id)
	err = d.redis.Del(key).Err()
	return
}
